package com.gavindon.android.view.video

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.leanback.widget.HorizontalGridView
import androidx.viewpager.widget.ViewPager
import com.airbnb.lottie.LottieAnimationView
import com.gavindon.android.R
import com.gavindon.android.adapters.VideoChapterAdapter
import com.gavindon.android.base.BaseFragment
import com.gavindon.android.base.INTENT_FRAGMENT_VIDEO
import com.gavindon.android.base.LazyFragment
import com.gavindon.android.entity.VideoTreeResp
import com.gavindon.android.utils.FreeStatus
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.support.v4.toast


/**
 * description: 视频详情下课时ViewPager fragment
 * Created by liNan on  2022-2-10 10:30
 */
class VideoDetailCourseFragment : LazyFragment() {
    override val layoutId = R.layout.fragment_course
    private lateinit var gridView: HorizontalGridView
    private lateinit var mAdapter: VideoChapterAdapter
    private val videoTreeResp: VideoTreeResp? by lazy {
        arguments?.getSerializable(INTENT_FRAGMENT_VIDEO) as VideoTreeResp
    }
    private var currentTabPos: Int = 0

    var callBackPlay: CallBackPlay? = null

    //上次播放课程的索引
    private var lastClickPos: Int = 0


    override fun onInit(view: View, savedInstanceState: Bundle?) {
        gridView = view.findViewById(R.id.course_gridview)
        //activity需要实现接口，进行调用播放章节
        callBackPlay = activity as CallBackPlay
        gridView.apply {
            setNumRows(1)
            setItemSpacing(20)
            setHasFixedSize(true)
        }
        //如果有tab.
        currentTabPos = arguments?.getInt("index", 0)!!
        vpChangeListener()
        //把第二节点和第三节点合并
        val newData = mutableListOf<VideoTreeResp>()
        videoTreeResp?.children?.forEach {
            if (it.children.isNullOrEmpty()) {
                newData.add(it)
            } else {
                it.children.forEach { three ->
                    three.chapterName = it.catalogName ?: ""
                    newData.add(three)
                }
            }
        }
        //把所有的状态更改为是否免费
        newData.forEach { it.isFree = videoTreeResp?.isFree.toString() }
        mAdapter = VideoChapterAdapter(R.layout.adapter_chapter, newData, currentTabPos)
        gridView.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, _, position ->
            val videoTreeResp = adapter.getItem(position) as VideoTreeResp
            val lessonId = videoTreeResp.linkObjId
            val freeViewing = videoTreeResp.freeViewing
            val act = (this.activity as VideoDetailActivity)
            //点击章节视频
            act.isItemClick = true
            callBackPlay?.fetchVideoItemData(lessonId, freeViewing, playPosition = position)
        }
        mAdapter.setDpadListener {
            //如果向上找不到view时手动设置tabLayout获取焦点/
            val act = (this.activity as VideoDetailActivity)
            if (act.hasTabLayout) {
                act.mTabLayout.requestFocus()
            } else {
                if (act.comboAdapter.data.isNullOrEmpty()) {
                    act.btnFullScreen.requestFocus()
                } else {
                    act.recommendComboRv.requestFocus()
                }
            }
        }
        //保存当前的适配器数据
        SaveAdapters.totalData[currentTabPos] = mAdapter
    }

    private fun vpChangeListener() {
        (activity as VideoDetailActivity).mViewPager.addOnPageChangeListener(object :
            ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                currentTabPos = position
                mAdapter.data.forEach {
                    it.isPlay = false
                }

                //如果划动到的页面是当前显示的viewpager,则播放动画
                if (currentTabPos == SaveCurrentView.lastTabPos) {
                    if (mAdapter.data.size > SaveCurrentView.lastPos) {
                        mAdapter.data[SaveCurrentView.lastPos].isPlay = true
                    }
                }
                mAdapter.notifyDataSetChanged()
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    //因为viewpager预加载原因，所以执行两次。
    var isEnter = true

    //自动播放
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun busAutoPlay(recordPlay: RecordPlay) {
        val adapter = SaveAdapters.totalData[SaveCurrentView.lastTabPos]
        adapter?.run {
            val next = recordPlay.position + 1
            if (next <= itemCount) {
                val itemView = recyclerView.layoutManager?.findViewByPosition(next)
                recyclerView.smoothScrollToPosition(next)
                itemView?.performClick()
            }
        }
    }

    var isAttach = false
    override fun onAttach(context: Context) {
        super.onAttach(context)
        isAttach = true
    }

    //点击item获取观看权限之后更新播放动画
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun busUpdatePlayView(playLottie: PlayLottie) {
        if (isAttach) {
            if (playLottie.tabPosition == SaveCurrentView.lastTabPos) {
                val current = playLottie.position
                //顺序不能颠倒 否则第一个不能显示播放动画
                if (mAdapter.itemCount > lastClickPos) {
                    mAdapter.data[lastClickPos].isPlay = false
//                    mAdapter.notifyItemChanged(lastClickPos)
                    mAdapter.notifyDataSetChanged()
                }
                if (mAdapter.itemCount > current) {
                    mAdapter.data[current].isPlay = true
//                    mAdapter.notifyItemChanged(current)
                }
                mAdapter.notifyDataSetChanged()
                lastClickPos = current
            }

            /*   mAdapter.data[lastClickPos].isPlay = false
               mAdapter.data[current].isPlay = true
               mAdapter.notifyItemChanged(current)
               mAdapter.notifyItemChanged(lastClickPos)*/

            SaveCurrentView.lastPos = lastClickPos
            SaveCurrentView.lastTabPos = playLottie.tabPosition
        }

    }

    //支付成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun busPayResultPlay(PayResultPlay: PayResultPlay) {
        //顺序不能颠倒 否则第一个不能显示播放动画
        mAdapter.data[PayResultPlay.position].isPlay = true
        mAdapter.notifyItemChanged(PayResultPlay.position)
        val view = mAdapter.recyclerView.layoutManager?.findViewByPosition(PayResultPlay.position)
        SaveCurrentView.lastPos = PayResultPlay.position
        view?.performClick()
        (activity as VideoDetailActivity).showHasBuy()
    }


    //定义点击章节播放回调接口
    interface CallBackPlay {
        //当前章节id,课程id,是否免费
        fun fetchVideoItemData(currentLessonId: String, freeViewing: String, playPosition: Int = 0)
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }


}

//保存当前播放视频的动画view
@SuppressLint("StaticFieldLeak")
object SaveCurrentView {
    var currentView: View? = null

    // 最后一次点击播放在当前tab下的位置
    var lastPos: Int = 0

    //最后一次点击播放在哪个tab下面
    var lastTabPos = 0
}

object SaveAdapters {
    val totalData = mutableMapOf<Int, VideoChapterAdapter>()
}
